<?php
declare (strict_types=1);

namespace app\command;

use app\api\logic\LogicalProcess;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;


class Receive extends Command
{
    protected function configure()
    {
        $this->setName('app\command\receive');

    }

    //悟空挖矿结算逻辑
    protected function execute(Input $input, Output $output)
    {
        //查询所有挖矿悟空
        $npc = Db::name("user_npc")->where("npc_id", 1)->whereNotNull("activate_time")->select()->toArray();
        if (empty($npc)) {
            $output->writeln('null');
            exit;
        }

        foreach ($npc as $v) {

            //查询悟空获得经书量
            $amount = (new LogicalProcess())->queryEarnings($v['user_id'])['amountTotal'];
            //生成领取记录
            $userGetRecord = Db::name("user_get_record")->insert([
                "user_id" => $v['user_id'],
                "amount" => $amount,
                "create_time" => datetime(time()),
            ]);
            //钱包变动
            (new LogicalProcess())->wallletChange($v['user_id'], $amount, 1, 1, 1, '悟空打怪');
            $user = Db::name("member")->where("id", $v['user_id'])->field("id,lv,group")->find();
            $userLvInfo = Db::name("league_config")->where("league_lv", $user['lv'])->find();
            if (!$user['group'] == 0 || !empty($user['group'])) {
                //转为数组
                $group = explode(",", $user['group']);
                foreach ($group as $pid) {
                    //查询上级用户等级
                    $parentLv = Db::name("member")->where("id", $pid)->value("lv");
                    if ($parentLv < $user['lv']) break;
                    //查询上级用户等级信息
                    $parentLvInfo = Db::name("league_config")->where("league_lv", $parentLv)->find();
                    $diffNum = 0;
                    if ($parentLv > $user['lv']) {
                        $diffNum = bcdiv($parentLvInfo['beat_monsters'] - $userLvInfo['beat_monsters'], "100", 6);
                    } else {
                        $diffNum = bcdiv($parentLvInfo['explore'], '100');
                    }
                    $subtract = bcmul(bcsub($v['allAmount'], $v['price'], 6), $diffNum);
                    (new LogicalProcess())->wallletChange($pid, $subtract, 8, 1, 1, '唐僧游历获得经书');
                }
            }
        }
        $output->writeln('success');
        exit;
    }
}